package cc.owoo.godpen.analysis.css;

import cc.owoo.godpen.analysis.html.Element;

import java.util.Queue;

/**
 * 属性选择器
 * Created by nimensei
 * 2022-06-04 下午 10:57
 */
public class AttributeSelector extends SelectorNode {
    private final String name;// 属性名称
    private final String condition;// 属性值
    private final Examine examine;// 比较规则

    public AttributeSelector(String name) {
        this(name, null, null);
    }

    public AttributeSelector(String name, String condition, Examine examine) {
        this.name = name;
        this.condition = condition;
        this.examine = examine;
    }

    @Override
    void selectElement(Element root, Queue<Element> elements) {
        root.getAllChildElement().forEach(element -> matchingElement(element, elements));
    }

    @Override
    void matchingElement(Element element, Queue<Element> elements) {
        if (examine == null) {
            if (element.hasAttribute(name))
                elements.add(element);
            return;
        }
        String value = element.getAttribute(name);
        if (value == null)
            return;
        if (examine.examine(value, condition))
            elements.add(element);
    }

    @Override
    public void stringify(StringBuilder string) {
        string.append('[');
        string.append(name);
        if (examine != null) {
            string.append(examine.getCharacter());
            string.append(condition);
        }
        string.append(']');
    }
}
